<template>
  <div class="container">
    <van-sticky>
      <div class="top-order-nav">
        <div class="nav-bar" :style="'padding-top:' + statusBarHeight + 'px;'">
          <van-icon class="mar-l-12 mar-r-8" name="arrow-left" size="20px" @click="$pt.navigateBack({ delta: -1 })" />
          <div class="search-bar" @click="$pt.navigateTo({url: '/pages/personal/order/search-view/main?listType=myOrder'})">搜索我的订单</div>
        </div>
      </div>
      <div class="tabs-bar line-size order-tabs">
        <div>
          <van-tabs :active="activeIndex" @change="tabClick" color="#FF4E23" :border="false">
            <van-tab :title="item" v-for="(item, index) in orderStatusList" :key="index"></van-tab>
          </van-tabs>
        </div>
        <div class="tab-more" @click="tabLayerShow">
          <span>筛选</span>
          <img v-if="fileSpace" class="width-15 height-13 mar-l-2" :src="fileSpace + '/images/home-category.png'" alt="">
        </div>
      </div>      
    </van-sticky>
    <div class="order-list" v-if="!nodata">
      <!-- 订单循环位置 orders为订单数组 -->
      <div class="order-item" v-for="(item, index) in orders" :key="index">
        <div class="flex flex-between pad-t-7 pad-b-7 pad-l-15 pad-r-15 border-b font-13">
          <div class="v-align-c">
            <div v-if="item.payType !== 0" class="flex flex-between">
              <img class="width-16 height-14" :src="item.payType === 5 ? fileSpace+'/images/pay-online.png' : fileSpace+'/images/pay-wx.png'" v-if="fileSpace" alt="">
              <span class="font-12 font-color-3 mar-l-6 mar-r-10">{{payTypeText[item.payType]}}</span>
            </div>
            <span v-if="item.enterprise">{{item.enterprise.enterpriseName}}</span>            
            <van-icon name="arrow" size="13px" />
            <span v-if="item.crossBorderOrderType === 2" class="font-12 mar-l-5 pad-l-5 pad-r-5 type-tag-cb">跨境保税</span>
            <div v-else class="font-12 mar-l-5 pad-l-5 pad-r-5 type-tag-cb">物流快递</div>
          </div>
          <div class="color-r">{{item.orderStatusName}}</div>
        </div>
        <div class="pad-l-15 pad-r-15" @click="$pt.navigateTo({ url: '/pages/personal/order/detail/main?orderId=' + item.orderId })">
          <div>
            <!-- sku循环位置 -->
            <div v-for="(goods, goodsIndex) in item.goodsList" :key="goodsIndex">
              <div class="flex pad-t-13.5 pad-b-13.5">
                <img class="radius-5 width-79 height-79" :src="goods[0].goodsImageUrl" alt="">
                <div class="flex-item mar-l-12.5 flex-col right-area">
                  <div class="line-2 height-38 mar-t-5">{{goods[0].goodsTitle}}</div>
                  <div class="font-13 color-r statusText" v-if="item.payTypeStatusTips">{{item.payTypeStatusTips}}</div>                  
                  <!-- <div v-if="item.cancelFlag === 1" class="refund-color font-13 mar-t-5">退款中</div> -->
                </div>
              </div>
              <div>
                <div class="flex flex-between pad-t-6 pad-b-6 pad-l-10 pad-r-15 sku-row" v-for="(sku, skuIndex) in goods" :key="skuIndex">
                  <div class="font-12 font-color-6">
                    <div class="flex sku-detail" v-if="sku.skuDetail">
                      <div>规格：</div>
                      <div class="width-200 line-1">{{sku.skuDetail}}</div>
                    </div>
                    <div>￥{{sku.goodsPrice}}<span v-if="item.unit">/{{item.unit}}</span></div>
                    <div v-if="sku.taxAmount && (sku.taxAmount * 1 > 0)">税费：￥{{ sku.taxAmount }}</div>
                  </div>
                  <div class="row-right">
                    <!--  退款关闭: -3、4、3（数量全退完）
                    退款：-2、-1、3(数量未退完)、''
                    退款中：0、1、2 -->
                    <div v-if="item.orderStatus !== -2 && item.orderStatus !== -1 && item.orderStatus !== 0 && item.orderStatus !== 1 && item.orderStatus !== 4">
                      <div class="refund-text refund-type-1" v-if="sku.afterSaleStatus===0 || sku.afterSaleStatus===1 || sku.afterSaleStatus===2" @click="linkToDetail(sku)">退款中</div>
                      <div class="refund-text refund-type-3" v-else-if="sku.afterSaleStatus===4" @click="linkToDetail(sku)">退款关闭</div>
                      <div class="refund-text refund-type-2" v-else-if="sku.afterSaleStatus===-2 || sku.afterSaleStatus===-1 || sku.afterSaleStatus===-3" @click="linkToDetail(sku)">退款失败</div>
                      <div class="refund-text refund-type-4" v-else-if="sku.afterSaleStatus===3" @click="linkToDetail(sku)">退款成功</div>
                    </div>
                    <div>×{{sku.goodsNum}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <!-- <div class="font-13 color-r flex flex-center pad-t-17 pad-b-17 border-b">
            <span>查看详情</span>
            <van-icon name="arrow" size="13px" color="#FF4E23" />
          </div> -->
          <div class="border-b">
            <div class="flex flex-between pad-t-11 pad-b-11">
              <div>共{{item.goodsNum}}件</div>
              <div>
                <span>合计：</span>
                <span class="color-r">￥{{item.actualPrice}}</span>
                <template v-if="item.taxAmount && (item.taxAmount * 1 > 0)">
                  <span class="pad-l-5">(含</span>
                  <span>税费¥{{ item.taxAmount }}</span>
                  <!-- <span>运费¥{{ item.freight }}</span> -->
                  <span>)</span>
                </template>
              </div>
            </div>
          </div>
        </div>
        <div class="btnbar pad-t-9 pad-b-9 pad-l-15 pad-r-15">
          <!-- 按钮，判断展示与否 -->
          <div class="btnbar-default btn" v-if="item.orderStatus === 0 || (item.crossBorderOrderType !== 2 && item.orderStatus === 1 && item.cancelFlag === 0) || (item.crossBorderOrderType === 2 && item.orderStatus === 1 && ((item.warehouseCustomsStatus === 4 || item.paymentOrderCustomsStatus === 7) || (item.warehouseCustomsStatus === 1 && item.paymentOrderCustomsStatus === 1) ) )" @click="cancelOrder(item)">取消订单</div>
          <div class="btnbar-default btn" v-if="item.orderStatus === 2 || item.orderStatus === 3 || item.orderStatus === 4" @click="queryExpress(item)">查看物流</div>
          <!-- 联系商家手机号码 -->
          <div class="btnbar-default btn" @click="$pt.makePhoneCall({phoneNumber: item.enterprise.phone})">联系商家</div>
          <div class="btnbar-pay btn" v-if="item.orderStatus === 0" @click="queryOrderInfo(item)">去付款</div>
          <div class="btnbar-pay btn" v-if="item.orderStatus === 2" @click="doReceiveGoods(item)">确认收货</div>
        </div>
      </div>
    </div>
    <div class="nodata" v-else>
      <img v-if="fileSpace" :src="fileSpace + '/images/w-icon-datanone-2.png'" class="width-118 height-102" alt="">
      <div class="title">暂无数据</div>
    </div>
    <!-- 筛选面板 -->
    <div @touchmove.prevent="">
      <van-popup
        :show="tabLayer"
        @close="tabLayer = false"
        position="right"
        custom-style="width: 80%; height: 100%;">
        <div class="popup-layer" style="padding-top:80px">
          <h3>订单类型</h3>
          <ul>
            <li v-for="(item, index) in orderType" :key="index">
              <div class="li-item" :class="{'active': orederCateIndex === index}" @click="changeOrderCate(item, index)">{{item}}</div>
            </li>
          </ul>
          <h3>配送方式</h3>
          <ul>
            <li v-for="(item, index) in orderTypeList" :key="index">
              <div class="li-item" :class="{'active': orederTypeIndex === index}" @click="changeOrderType(index)">{{item}}</div>
            </li>
          </ul>
          <h3>订单状态</h3>
          <ul>
            <li v-for="(item, index) in orderStatusList" :key="index">
              <div class="li-item" @click="changeOrderStatus(index)" :class="{'active': activeStatusIndex === index}">{{item}}</div>
            </li>
          </ul>
          <div class="bottom-btn flex flex-between pad-l-15 pad-r-15" style="position:fixed">
            <div class="reset-btn" @click.stop="resetCondition">重置</div>
            <div class="comfirm-btn" @click.stop="sureSerch">确定</div>
          </div>
        </div>
      </van-popup>
    </div>
  </div>
</template>
<script>
  import { pageOrder, doReceiveGoods, updateOrderStatByMemberId, checkCancelPaidOrder, cancelOrder } from '@/api/personal'

  export default {
    data() {
      return {
        activeIndex: 0,
        orderStatusQuery: '',
        orderStatusList: ['全部', '待付款', '待发货', '待收货', '已收货', '已完成', '已取消'],
        orders: [],
        nodata: false,
        pullLoad: {
          loading: false,
          finished: false
        },
        params: {
          size: 10,
          currentPage: 1
        },
        statusBarHeight: 0,
        firstLoad: true,
        payTypeText: {1: '微信支付', 5: '线下支付'},
        tabLayer: false,
        tabRiSearch: false,
        orederCateIndex: 0,
        orderType: ['全部', '普通订单'],
        orderTypeList: ['全部', '物流快递'],
        orederTypeIndex: 0,
        activeStatusIndex: 0,
        deliveryType: '', // 配送方式 1：物流快递 2: 门店自提 4:社区自提 5:门店配送  门店自提---自营商品
        deliveryTypeArr: ['物流快递', '门店自提', '社区团购', '到店自提', '门店配送'],
        crossBorderOrderType: ''
      }
    },
    onLoad() {
      // 初始化data
      Object.assign(this.$data, this.$options.data())
      this.statusBarHeight = this.$pt.getSystemInfoSync()['statusBarHeight']
    },
    onShow() {
      // 是否有跨境增值功能
      this.tabRiSearch = false
      if (this.$pt.getStorageSync('cbFlag')) {
        this.orderType = ['全部', '普通订单', '跨境订单']
      } else {
        this.orderType = ['全部', '普通订单']
      }
      this.params.currentPage = 1
      this.orderStatusQuery = ''
      this.orders = []
      if (this.firstLoad) {
        const type = this.getCurrentPage().query.type
        switch (type) {
          case 'wPay':
            // 待付款
            this.activeIndex = 1
            break
          case 'wShipped':
            // 待发货
            this.activeIndex = 2
            break
          case 'wReceive':
            // 待收货
            this.activeIndex = 3
            break
          case 'wOver':
            // 已完成
            this.activeIndex = 5
            break
        }
        this.firstLoad = false
      }
      this.pageOrder()
    },
    onPullDownRefresh() {
      this.params.currentPage = 1
      this.orders = []
      this.pullLoad.finished = false
      this.orderStatusQuery = ''
      this.pageOrder()
      setTimeout(() => {
        this.$pt.stopPullDownRefresh()
      }, 500)
    },
    onReachBottom() {
      // 触底刷新
      if (!this.pullLoad.finished) {
        this.pageOrder()
      }
    },
    methods: {
      tabClick(e) {
        if (this.tabRiSearch) return
        // tab变化事件
        this.params.currentPage = 1
        this.activeIndex = e.mp.detail.index
        this.pullLoad.finished = false
        this.orders = []
        this.orderStatusQuery = ''
        this.pageOrder()
      },
      // 打开筛选层
      tabLayerShow() {
        this.tabRiSearch = true
        this.tabLayer = true
        this.activeStatusIndex = this.activeIndex
      },
      // 关闭筛选层
      onPopupClose() {
        this.tabLayer = false
      },
      changeOrderCate(item, index) {
        this.orederCateIndex = index
      },
      changeOrderType(index) {
        this.orederTypeIndex = index
      },
      changeOrderStatus(index) {
        this.activeStatusIndex = index
      },
      resetCondition() {
        this.orders = []
        this.orederCateIndex = 0
        this.orederTypeIndex = 0
        this.activeStatusIndex = 0
        this.activeIndex = 0
        this.crossBorderOrderType = ''
        this.deliveryType = ''
        this.params.currentPage = 1
        this.pullLoad.finished = false
        this.tabLayer = false
        this.pageOrder()
      },
      sureSerch() {
        switch (this.orederCateIndex) {
          default:
          case 0:
            // 全部
            this.crossBorderOrderType = ''
            break
          case 1:
            // 普通订单
            this.crossBorderOrderType = 1
            break
          case 2:
            // 跨境保税
            this.crossBorderOrderType = 2
            break
        }
        this.params.currentPage = 1
        this.orders = []
        this.tabLayer = false
        this.pullLoad.finished = false
        this.pageOrder()
      },
      cancelOrder(item) {
        // 取消订单事件
        // 订单里面都没有发货才可以取消订单，到订单取消页面
        // 否则提示联系卖家处理
        if (item.orderStatus === 0) {
          this.$pt.showModal({
            title: '温馨提示',
            content: '确认取消订单?',
            success: res => {
              if (res.confirm) {
                cancelOrder({orderId: item.orderId}).then(response => {
                  if (response.isError) return
                  this.$pt.navigateTo({url: `/pages/personal/order/detail/main?orderId=${item.orderId}`})
                })
              }
            }
          })
        } else {
          checkCancelPaidOrder({orderId: item.orderId}).then(response => {
            if (response.isError) return
            this.$pt.navigateTo({url: `/pages/personal/order/cancel-order/main?memberId=${item.memberId}&orderId=${item.orderId}`})
          })
        }
      },
      queryOrderInfo(order) {
        console.log(order)
        // 去支付(0:还没有选择任意一种支付方式，需重新进入收银台选择)
        if (order.payType === 0) {
          this.$pt.navigateTo({url: `/pages/shop/counter/main?orderId=${order.orderId}&price=${order.actualPrice}`})
        }
        if (order.payType === 1) {
          console.log(order)
          this.$pt.navigateTo({ url: '/pages/personal/order/detail/main?orderId=' + order.orderId })
        }
        if (order.payType === 5) {
          this.$pt.navigateTo({url: `/pages/shop/counter/offline-payments/main?orderId=${order.orderId}&price=${order.actualPrice}`})
        }
        // this.$pt.navigateTo({ url: '/pages/personal/order/detail/main?orderId=' + order.orderId })
      },
      doReceiveGoods(order) {
        // 确认收货
        const that = this
        this.$pt.showModal({
          content: '是否确认收货？',
          success(res) {
            if (res.confirm) {
              doReceiveGoods({ memberId: order.memberId, orderId: order.orderId }).then(response => {
                if (response.isError) return
                that.orders = []
                that.params.currentPage = 1
                that.pullLoad.finished = false
                that.orderStatusQuery = ''
                that.pageOrder()
                const data = response.data
                const goodsNum = order.orderGoodsList.length
                const appName = data.appName || ''
                const appId = data.appId || ''
                console.log('列表页：', data.appName, '类型判段', typeof data.appName)
                const params = 'orderId=' + order.orderId + '&goodsNum=' + goodsNum + '&appName=' + appName + '&appId=' + appId + '&receivedTime=' + data.receivedTime
                that.$pt.navigateTo({ url: '/pages/personal/order/confirm-receipt/main?' + params })
              })
            }
          }
        })
      },
      queryExpress(order) {
        // 查看物流
        this.$pt.navigateTo({ url: '/pages/personal/order/express/main?orderId=' + order.orderId })
      },
      pageOrder() {
        let index = null
        if (this.tabRiSearch) {
          index = this.activeStatusIndex
        } else {
          index = this.activeIndex
        }
        switch (index) {
          default:
          case 0:
            // 全部
            this.orderStatusQuery = ''
            break
          case 1:
            // 待付款
            this.orderStatusQuery = '0'
            break
          case 2:
            // 待发货
            this.orderStatusQuery = '1'
            break
          case 3:
            // 待收货
            this.orderStatusQuery = '2'
            break
          case 4:
            // 已收货
            this.orderStatusQuery = '3'
            break
          case 5:
            // 已完成
            this.orderStatusQuery = '4'
            break
          case 6:
            // 已取消
            this.orderStatusQuery = '-1,-2'
            break
        }
        const params = {
          memberId: this.getShowBuyCard ? this.getCustomerId : this.getMemberId,
          orderStatusList: this.orderStatusQuery,
          deliveryType: 1,
          crossBorderOrderType: this.crossBorderOrderType,
          currentPage: this.params.currentPage,
          size: 10
        }
        this.nodata = false
        this.$pt.showLoading()
        pageOrder(params).then(response => {
          this.$pt.hideLoading()
          if (response.isError) return
          if (this.tabRiSearch) {
            this.activeIndex = this.activeStatusIndex
          }
          this.tabRiSearch = false
          response.data.records.forEach(order => {
            switch (order.orderStatus) {
              case 0:
                order.orderStatusName = '待付款'
                break
              case 1:
                order.orderStatusName = '待发货'
                break
              case 20:
                order.orderStatusName = '待发货'
                break
              case 2:
                order.orderStatusName = '待收货'
                break
              case 3:
                order.orderStatusName = '已收货'
                break
              case 4:
                order.orderStatusName = '已完成'
                break
              case -1:
                order.orderStatusName = '已取消'
                break
              case -2:
                order.orderStatusName = '已取消'
                break
              default:
                break
            }
            const goodsMap = {}
            order.orderGoodsList.forEach(orderGoods => {
              let skuList = goodsMap[orderGoods.goodsId]
              if (!skuList) {
                skuList = []
              }
              skuList.push(orderGoods)
              goodsMap[orderGoods.goodsId] = skuList
            })
            order.goodsList = []
            for (let key in goodsMap) {
              order.goodsList.push(goodsMap[key])
            }
            if (order.enterprise && order.enterprise.enterpriseName && order.enterprise.enterpriseName.length > 10) {
              order.enterprise.enterpriseName = this.$utils.getStrByLength(order.enterprise.enterpriseName, 20)
            }
            this.orders.push(order)
          })
          // console.log('orders', this.orders)
          if (this.orders.length === 0) {
            this.nodata = true
          }
          this.params.currentPage++
          if (this.orders.length === 0 || this.orders.length >= response.data.total) {
            this.pullLoad.finished = true
          }
        })
        updateOrderStatByMemberId({
          memberId: this.getShowBuyCard ? this.getCustomerId : this.getMemberId,
          memberType: 2,
          orderType: 2,
          orderStatusList: this.orderStatusQuery
        }).then(response => {
        })
      },
      linkToDetail(sku) {
        console.log('sku', sku)
        // sku.orderId = this.order.orderId
        let value = JSON.stringify(sku)
        this.$pt.navigateTo({url: `/pages/personal/order/refund-detail/main?sku=${value}`})
      }
    }
  }
</script>
<style lang="less" scoped>
.top-order-nav{
  position: relative;
  z-index: 10000;
}
.tabs-bar {
  position: relative;
  min-height: 38px;
  padding-right: 70px;
  box-sizing: border-box;
  width: 100%;
  position: relative;
  z-index: 10;
  background: #fff;
  .tab-more{
    width: 50px;
    height: 25px;
    position: absolute;
    right: 0;
    top: 6px;
    z-index: 11;
    display: flex;
    align-items: center;
    padding-left: 5px;
    border-left: 2px solid #dcdcdc;
    &.tab-more-and{
      top: 3px;
    }
  }
}
.popup-layer{
  height: 100%;
  position: fixed;
  box-sizing: border-box;
  // padding-bottom: 70px;
  overflow-y: scroll;
  h3{
    line-height: 1;
    padding: 16px 15px 0;
    font-size: 15px;
    color: #333;
  }
  ul{
    display: flex;
    align-items: center;
    justify-content: flex-start;
    flex-wrap: wrap;
    padding: 5px 15px 0;
    li{
      // flex-shrink: 0;
      margin-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      flex: 0 0 calc(100% / 3);
      &:nth-child(3n + 1) {
        justify-content: flex-start;
      }
      &:nth-child(3n) {
        justify-content: flex-end;
      }
      .li-item{
        width: 76px;
        height: 32px;
        border-radius: 16px;
        background-color: #F5F5F5;
        font-size: 12px;
        color: #333;
        text-align: center;
        line-height: 32px;
        box-sizing: border-box;
          &.active{
          border: 1px solid #FFE200;
          background-color: #FFFBD8;
          width: 74px;
          height: 30px;
          line-height: 30px;
        }
      }
    }
  }
  .bottom-btn{
    // position: sticky;
    bottom: 0;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    font-size: 16px;
    text-align: center;
    background-color: #fff;
    padding: 10px 15px;
    .reset-btn{
      width: 106px;
      height: 44px;
      border-radius: 22px;
      line-height: 44px;
      background-color: #F5F5F5;
      color: #666;
    }
    .comfirm-btn{
      width: 152px;
      height: 44px;
      line-height: 44px;
      border-radius: 22px;
      background-color: #FFE100;
      color: #333;
    }
  }
}
.type-tag-cb{
  border-radius: 4px;
  background: #ff4c17;
  color: #fff;
}
.nav-bar{
  height: 44px;
  background: white;
  display: flex;
  align-items: center;
  .search-bar{
    height: 35px;
    width: 228px;
    border-radius: 17.5px;
    line-height: 35px;
    padding-left: 15px;
    box-sizing: border-box;
    color: #999999;
    background: #EEEEEE;
  }
}
.order-item{
  background: white;
  margin-top: 10px;
}
.border-b{
  border-bottom: 1px solid #E9E9E9;
}
.color-r{
  color: #FF4E23;
}
.sku-row{
  border-radius: 4px;
  background: #F8F8F8;
  margin-top: 7px;
  &:first-child{
    margin-top: 0;
  }
  .sku-detail{
    .line-1{
      line-height: unset;
    }
  }
  .row-right{
    display: flex;
    flex-direction: column;
    align-items: flex-end;
  }
  .refund-text{
    font-size: 12px;
    text-decoration: underline;
  }
  .refund-type-1{
    color: #409EFF;
  }
  .refund-type-2{
    color: #FF0000;
  }
  .refund-type-3{
    color: #6F7073;
  }
  .refund-type-4{
    color: #217D00;
  }
}
.refund-color{
  color: #E6A23C;
}
.btnbar{
  display: flex;
  align-items: center;
  justify-content: flex-end;
  .btn{
    padding: 10px 18px;
    font-size: 13px;
    border-radius: 17px;
    line-height: 1;
    margin-left: 9px;
  }
  &-default{
    background: white;
    color: #999999;
    border: 1px solid #B6B6B6;
  }
  &-pay{
    padding: 11px 18px !important;
    background: linear-gradient(to right, #FF9048, #FF4E23);
    color: white;
  }
}
.radius-5{
  border-radius: 5px;
}
.nodata{
  padding-top: 130px;
  img{
    margin: 0 auto;
  }
  .title{
    margin-top: 35px;
    text-align: center;
    font-size: 18px;
  }
}
// 修改vant tabs样式
.order-tabs{
  /deep/ .van-tabs--line{
    .van-tabs__wrap{
      height: 40px;
    }
  }
  /deep/ .van-tab {
    line-height: 40px;
  }
}
.right-area {
  justify-content: space-between;
  .statusText {
    display: flex;
    justify-content: flex-end;
  }
}
</style>
